package ru.arriah.servicedesk.web.chief.action;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Locale;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.RequestPriorityBean;
import ru.arriah.servicedesk.bean.RequestTypeBean;
import ru.arriah.servicedesk.bean.TaskBean;
import ru.arriah.servicedesk.bean.error.RequestFormErrorBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;

public class ProcessRequestEditFormAction extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;
   protected EmployeeManagerLocalHome employeeManagerLocalHome;
   protected GroupManagerLocalHome groupManagerHome;   
   protected RequestFormErrorBean requestFormErrorBean;

   public ProcessRequestEditFormAction() throws NamingException {
      super();
      
      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
      
      groupManagerHome =
        Utils.getGroupManagerHomeInterface();
      
      employeeManagerLocalHome =
        Utils.getEmployeeManagerHomeInterface();      
   }
   
   
   private boolean isValid(
     RequestBean requestBean, 
     RequestManagerLocalObject requestManager
   ) {
     boolean valid = true;
     
     requestFormErrorBean = new RequestFormErrorBean();          
     RequestBean rb = 
       requestManager.selectRequest(requestBean.getId());
     
     if (requestBean.getDispatcherText() == null || requestBean.getDispatcherText().equals("")) {
       requestFormErrorBean.setDispatcherText(
         config.getProperty("ERROR.REQUESTFORM.DISPATCHERTEXT")
       );
       valid = false;
     }     
     
     if (requestBean.getRequestTypeId() == 0) {
       requestFormErrorBean.setRequestType(
         config.getProperty("ERROR.REQUESTFORM.REQUESTTYPE")
       );
       valid = false;
     }
     
     if (requestBean.getApproxEndDate() == null) {
       requestFormErrorBean.setApproxEndDate(
         config.getProperty("ERROR.REQUESTFORM.APPROX_END_DATE")
       );
       valid = false;
     } else {              
       if (
          rb.getRegistrationDate().after(requestBean.getApproxEndDate()) && 
          !Utils.isSameDay(rb.getRegistrationDate(), requestBean.getApproxEndDate())
       ) {
         requestFormErrorBean.setApproxEndDate(
           String.format(
             config.getProperty("ERROR.REQUESTFORM.REGDATE_AFTER_END"),
             rb.getRegistrationDate()
           )
         );
         valid = false;
       }
     }    
     
     if (requestBean.getPriority() == 0) {
       requestFormErrorBean.setPriority(
         config.getProperty("ERROR.REQUESTFORM.PRIORITY")
       );
       valid = false;
     }
     
     return valid;
   }

   
   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {
       RequestBean requestBean = new RequestBean();
            
       DateFormat dateformat = 
          DateFormat.getDateInstance(
             DateFormat.SHORT, 
             new Locale("ru")
          );

       int userId = Utils.getUserId(request);       
       int requestId = idVal(request.getParameter("id"));       
       
       requestBean.setId(requestId);
       requestBean.setClientText(request.getParameter("text"));
       requestBean.setDispatcherText(request.getParameter("dispatcherText"));                     
       requestBean.setRequestTypeId(idVal(request.getParameter("requesttype_id")));                            
       requestBean.setPriority(idVal(request.getParameter("priority")));
       requestBean.setComment(request.getParameter("comment"));
       
       try {
         requestBean.setApproxEndDate(
           dateformat.parse(request.getParameter("approxEndDate"))
         );
       } catch (Exception e) {}
       
       RequestManagerLocalObject requestManager = 
         requestManagerHome.create();
       
       EmployeeManagerLocalObject employeeManager = 
         employeeManagerLocalHome.create();
       
       if (!isValid(requestBean, requestManager)) { 
         
         GroupManagerLocalObject groupManager = 
           groupManagerHome.create();                        
         
         Collection<RequestTypeBean> requestTypesList = 
           requestManager.selectRequestTypes();                 
         
         Collection<RequestPriorityBean> priorityList = 
           requestManager.selectPriorityList();                                    
         
         groupManager.remove();
         
         addErrorMessage(
           request,
           config.getProperty("ERROR.REQUESTFORM_FIELDS_INVALID")
         );
         
         request.setAttribute("priorityList", priorityList);
         request.setAttribute("requestTypesList", requestTypesList);         
         request.setAttribute("requestBean", requestBean);
         request.setAttribute("error", requestFormErrorBean);                  

         return actionMapping.getFailureTarget();
       }
                
       
       RequestBean oldRequest = requestManager.selectRequest(requestId);                     
       requestBean.setLeadExecutorId(oldRequest.getLeadExecutorId());
       requestBean.setStatusId(oldRequest.getStatusId());       
       
       if (requestManager.updateRequestByLeadExecutor(requestBean, userId))
         
          addInfMessage(
            request,
            config.getProperty("INF.REQUEST_UPDATED")
          );
       
       else 
         addErrorMessage(
            request,
            config.getProperty("ERROR.REQUEST_NOT_UPDATED")
         );
       
       requestBean = 
         requestManager.selectRequestDetails(requestId);
       Collection<TaskBean> tasksList = 
          requestManager.selectTasksByRequest(
             requestId,
             "executor",
             "ASC"
          );
             
       employeeManager.remove();              
       requestManager.remove();
       
       request.setAttribute("requestBean", requestBean);
       request.setAttribute("tasksList", tasksList);
             
       return actionMapping.getSuccessTarget();
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}